/*
 * BSM6.0
 *
 * Copyright 2012-2013 (C) SINODATA CO., LTD. All Rights Reserved.
 */
package com.sinodata.bsm.center.web.action.order;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;

import com.sinodata.bsm.center.bean.ResBean;
import com.sinodata.bsm.center.cache.EventTypeCache;
import com.sinodata.bsm.center.cache.ResCache;
import com.sinodata.bsm.center.purview.FunctionConstants;
import com.sinodata.bsm.center.purview.UserFunctionValidate;
import com.sinodata.bsm.center.service.order.ProcessRuleService;
import com.sinodata.bsm.center.util.AnalyzePropertiesUtil;
import com.sinodata.bsm.center.util.web.Struts2Utils;
import com.sinodata.bsm.center.web.action.BaseAction;
import com.sinodata.bsm.common.constants.EventConstants;
import com.sinodata.bsm.common.constants.NotifyConstants;
import com.sinodata.bsm.common.vo.ProcessEventTypeRule;
import com.sinodata.bsm.common.vo.ProcessExcludeResRule;
import com.sinodata.bsm.common.vo.ProcessRule;
import com.sinodata.bsm.common.vo.Res;

/**
 * <p>
 * Description: 
 * </p>
 *
 * @author dongyushi
 * @version 1.0

 * <p>
 * History: 
 *
 * Date                     Author         Version     Description
 * ---------------------------------------------------------------------------------
 * 2013-3-13 上午9:38:47          dongyushi        1.0         To create
 * </p>
 *
 * @since 
 * @see     
 */
public class ProcessRuleAction extends BaseAction<ProcessRule> {

    private static final long serialVersionUID = 9204743621168274998L;

    /**
     * 发送工单实现类的配置文件
     */
    private static final String filename = "WEB-INF/conf/send-process-impclass.properties";
    @Autowired
    private ProcessRuleService processRuleService;
    @Autowired
    private ResCache resCache;
    @Autowired
    private EventTypeCache eventTypeCache;

    private Long id;
    private ProcessRule entity;

    public String common() {
        Struts2Utils.getRequest().setAttribute("resId", request.getParameter("id"));
        return "common";
    }

    @Override
    public ProcessRule getModel() {
        return entity;
    }

    @Override
    public String list() throws Exception {
        Long resId = Long.valueOf(request.getParameter("resId"));
        List<ProcessRule> list = processRuleService.findAllByRes(resId);
        JSONObject json = new JSONObject();
        JSONArray array = new JSONArray();
        boolean sysManager = UserFunctionValidate.sysFunctionValidate(FunctionConstants.SYSTEM_MANAGER);
        for (ProcessRule workOrder : list) {
            JSONObject obj = new JSONObject();
            obj.element("op", sysManager ? "<div style='width: 80px'>&nbsp;&nbsp;&nbsp;<a href='javascript:" + ((workOrder.getStatus() == 0) ? "start" : "stop") + "(" + workOrder.getId() + ");'><img src='../style/default/bsm/images/" + ((workOrder.getStatus() == 0) ? "start.gif' title='启用'" : "stop.gif' title='禁用'") + "></a>&nbsp;<a href='javascript:update(" + workOrder.getId() + ");'><img src='../style/default/bsm/images/edit.gif' title='修改'></a>&nbsp;<a href='javascript:del(" + workOrder.getId() + ");'><img src='../style/default/bsm/images/delete.gif' title='删除'></a><div>" : " ");
            obj.element("id", workOrder.getId());
            obj.element("resName", ResBean.get(workOrder.getResId()).res().getName());
            obj.element("name", workOrder.getName());
            obj.element("eventLevels", transEventLevel(workOrder.getEventLevels()));
            obj.element("sendClass", workOrder.getSendClass());
            obj.element("status", NotifyConstants.getRuleStatusDesc(workOrder.getStatus()));
            array.add(obj);
        }
        json.element("aaData", array);
        renderText(json.toString());
        return null;
    }

    public String add() {
        Long resId = Long.parseLong(request.getParameter("resId"));
        Struts2Utils.getRequest().setAttribute("resId", resId);
        Struts2Utils.getRequest().setAttribute("resName", resCache.get(resId) == null ? "请选择资源" : resCache.get(resId).getName());
        AnalyzePropertiesUtil prop = AnalyzePropertiesUtil.getInstance();
        Map<String, String> map = prop.getProperties(filename);
        List<String> names = new ArrayList<String>();
        if (map != null && map.size() > 0) {
            for (String name : map.keySet()) {
                names.add(name);
            }
        }
        Struts2Utils.getRequest().setAttribute("classNames", names);
        return "add";
    }

    public String addResExclude() {
        Struts2Utils.getRequest().setAttribute("workOrderId", request.getParameter("workOrderId"));
        Struts2Utils.getRequest().setAttribute("resId", request.getParameter("resId"));
        return "excluderes";
    }

    public String delResExclude() throws Exception {
        processRuleService.deleteResExcludeById(Long.valueOf(request.getParameter("id")));
        return null;
    }

    public String listResExclude() throws Exception {
        List<ProcessExcludeResRule> list = new ArrayList<ProcessExcludeResRule>();
        if (!request.getParameter("workOrderId").equals("")) {
            list = processRuleService.getWorkOrderExcludeResByWorkOrderId(Long.parseLong(request.getParameter("workOrderId")));
        }
        String resName = "";
        if (!request.getParameter("resId").equals("")) {
            Res res = resCache.get(Long.valueOf(request.getParameter("resId")));
            resName = res != null ? res.getName() : "";
        }
        JSONObject json = new JSONObject();
        json.element("iTotalRecords", list.size());
        json.element("iTotalDisplayRecords", list.size());
        JSONArray array = new JSONArray();
        for (ProcessExcludeResRule workOrderExcludeRes : list) {
            JSONObject obj = new JSONObject();
            obj.element("op", "<div style='width: 50px'>&nbsp;&nbsp;&nbsp;<a href='javascript:delResExclude(" + workOrderExcludeRes.getId() + ");'><img src='../style/default/bsm/images/delete.gif' title='删除'></a><div>");
            obj.element("id", workOrderExcludeRes.getId());
            obj.element("data", resName + "-->" + resCache.get(workOrderExcludeRes.getResId()).getName());
            array.add(obj);
        }
        json.element("aaData", array);
        renderText(json.toString());
        return null;
    }

    public String saveResExclude() throws Exception {
        if (request.getParameter("workOrderId").equals("")) {
            renderText("false");
            return null;
        }
        String resId = request.getParameter("resId");
        String[] array = resId.split(",");
        String workOrderId = request.getParameter("workOrderId");
        List<ProcessExcludeResRule> list = new ArrayList<ProcessExcludeResRule>();
        List<ProcessExcludeResRule> listOld = processRuleService.getWorkOrderExcludeResByWorkOrderId(Long.valueOf(workOrderId));
        List<Long> resIdList = new ArrayList<Long>();
        if (listOld != null) {
            for (ProcessExcludeResRule workOrderExcludeRes : listOld) {
                resIdList.add(workOrderExcludeRes.getResId());
            }
        }
        for (String s : array) {
            if (!resIdList.contains(Long.valueOf(s))) {
                ProcessExcludeResRule workOrderExcludeRes = new ProcessExcludeResRule();
                workOrderExcludeRes.setWorkOrderId(Long.valueOf(workOrderId));
                workOrderExcludeRes.setResId(Long.valueOf(s));
                list.add(workOrderExcludeRes);
            }
        }
        processRuleService.batchAddWorkOrderExcludeRes(list);
        return null;
    }

    private String transEventLevel(String levels) {
        StringBuilder sb = new StringBuilder("");
        if (levels != null && !"".equals(levels)) {
            String[] temp = levels.split("[,]");
            for (int i = 0; i < temp.length; i++) {
                if (i != 0) {
                    sb.append(",");
                }
                sb.append(EventConstants.getLevelDesc(Integer.valueOf(temp[i])));

            }
        }
        return sb.toString();
    }

    @Override
    public String input() throws Exception {
        Struts2Utils.getRequest().setAttribute("resId", request.getParameter("resId"));
        Struts2Utils.getRequest().setAttribute("resName", resCache.get(Long.valueOf(request.getParameter("resId"))).getName());
        ProcessRule workOrder = processRuleService.getWorkOrderById(Long.valueOf(request.getParameter("id")));
        List<ProcessEventTypeRule> list = processRuleService.getWorkOrderEventTypeByWorkOrderId(workOrder.getId());
        StringBuffer eventType = new StringBuffer("");
        StringBuffer eventTypeName = new StringBuffer("");
        if (list != null) {
            for (ProcessEventTypeRule workOrderEventType : list) {
                eventType.append(workOrderEventType.getEventTypeId()).append(",");
                eventTypeName.append(eventTypeCache.get(workOrderEventType.getEventTypeId()).getName()).append(",");
            }
        }
        if (eventType.length() != 0) {
            eventType.delete(eventType.lastIndexOf(","), eventType.length());
            eventTypeName.delete(eventTypeName.lastIndexOf(","), eventTypeName.length());
        }
        AnalyzePropertiesUtil prop = AnalyzePropertiesUtil.getInstance();
        Map<String, String> map = prop.getProperties(filename);
        List<String> names = new ArrayList<String>();
        if (map != null && map.size() > 0) {
            for (String name : map.keySet()) {
                names.add(name);
            }
        }
        Struts2Utils.getRequest().setAttribute("classNames", names);
        Struts2Utils.getRequest().setAttribute("eventTypeName", eventTypeName.toString());
        Struts2Utils.getRequest().setAttribute("eventType", eventType.toString());
        Struts2Utils.getRequest().setAttribute("radio", eventType.length() == 0 ? "all" : "other");
        Struts2Utils.getRequest().setAttribute("workOrder", workOrder);
        return "update";
    }

    @Override
    public String save() throws Exception {
        entity.setStatus(NotifyConstants.RULE_STATUS_ENABLE);
        entity.setEventLevels(request.getParameter("eventLevel"));
        if (entity.getId() != null) {//修改
            if (processRuleService.getWorkOrderById(entity.getId()) != null) {
                processRuleService.update(entity);
                //自定义
                if (!request.getParameter("eventTypeId").equals("")) {
                    List<ProcessEventTypeRule> listOld = processRuleService.getWorkOrderEventTypeByWorkOrderId(entity.getId());
                    if (listOld != null && listOld.size() != 0) {
                        processRuleService.delEventType(listOld);
                    }
                    String[] array = request.getParameter("eventTypeId").split(",");
                    List<ProcessEventTypeRule> list = new ArrayList<ProcessEventTypeRule>();
                    for (String eventTypeId : array) {
                        ProcessEventTypeRule workOrderEventType = new ProcessEventTypeRule();
                        workOrderEventType.setWorkOrderId(entity.getId());
                        workOrderEventType.setEventTypeId(Long.valueOf(eventTypeId));
                        list.add(workOrderEventType);
                    }
                    processRuleService.addEventType(list);
                } else {
                    List<ProcessEventTypeRule> listOld = processRuleService.getWorkOrderEventTypeByWorkOrderId(entity.getId());
                    if (listOld != null && listOld.size() != 0) {
                        processRuleService.delEventType(listOld);
                    }
                }
                JSONObject ob = new JSONObject();
                ob.element("flag", true);
                ob.element("workOrderId", entity.getId());
                Struts2Utils.renderJson(ob.toString());
            } else {
                JSONObject ob = new JSONObject();
                ob.element("flag", false);
                Struts2Utils.renderJson(ob.toString());
            }
        } else {//新增
            processRuleService.add(entity);

            if (!request.getParameter("eventTypeId").equals("")) {
                String[] array = request.getParameter("eventTypeId").split(",");
                List<ProcessEventTypeRule> list = new ArrayList<ProcessEventTypeRule>();
                for (String eventTypeId : array) {
                    ProcessEventTypeRule workOrderEventType = new ProcessEventTypeRule();
                    workOrderEventType.setWorkOrderId(entity.getId());
                    workOrderEventType.setEventTypeId(Long.valueOf(eventTypeId));
                    list.add(workOrderEventType);
                }
                processRuleService.addEventType(list);
            }
            JSONObject ob = new JSONObject();
            ob.element("workOrderId", entity.getId());
            ob.element("flag", true);
            Struts2Utils.renderJson(ob.toString());
        }
        return null;
    }

    public String checkName() throws Exception {
        String resId = request.getParameter("resId");
        String name = new String(request.getParameter("name").getBytes("ISO-8859-1"), "UTF-8");
        name = name.replace(" ", "----");
        name = java.net.URLDecoder.decode(name, "UTF-8");
        name = name.replace("----", "+");
        String oldName = "";
        if (request.getParameter("oldName") != null && !request.getParameter("oldName").equals("")) {
            oldName = new String(request.getParameter("oldName").getBytes("ISO-8859-1"), "UTF-8");
            oldName = oldName.replace(" ", "----");
            oldName = java.net.URLDecoder.decode(oldName, "UTF-8");
            oldName = oldName.replace("----", "+");
        }
        if (!name.equals(oldName)) {
            if (processRuleService.checkName(Long.valueOf(resId), name)) {
                renderText("true");
            } else {
                renderText("false");
            }
        } else {
            renderText("true");
        }
        return null;
    }

    public String disable() {
        if (request.getParameter("id") != null) {
            processRuleService.disable(Long.parseLong(request.getParameter("id")));
            renderText("true");
        } else {
            renderText("false");
        }
        return null;
    }

    public String enable() {
        if (request.getParameter("id") != null) {
            processRuleService.enable(Long.parseLong(request.getParameter("id")));
            renderText("true");
        } else {
            renderText("false");
        }
        return null;
    }

    @Override
    public String delete() throws Exception {
        if (request.getParameter("id") != null) {
            processRuleService.delete(Long.parseLong(request.getParameter("id")));
            renderText("true");
        } else {
            renderText("false");
        }
        return null;
    }

    public String checkDeleted() {
        JSONObject ob = new JSONObject();
        if (processRuleService.getWorkOrderById(Long.valueOf(request.getParameter("id"))) == null) {
            ob.element("flag", false);
        } else {
            ob.element("flag", true);
        }
        Struts2Utils.renderJson(ob.toString());
        return null;
    }

    @Override
    protected void prepareModel() throws Exception {
        if (id != null) {
            entity = processRuleService.getWorkOrderById(id);
            if (entity == null) {
                entity = new ProcessRule();
            }
        } else {
            entity = new ProcessRule();
        }
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }
}
